package com.company.chatting;

import com.company.utils.MyException;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc
 */
public class ChatClient {
//    客户端使用同一个socket
    private static Socket socket;
    //一个socket下的oos只能有一个oos
    private static boolean isconn = false;
    public static void turnOffState(){
        isconn = false;
    }
    public static void main(String[] args) {
        while (!isconn) {
            try {
                connect();
            } catch (Exception e) {
                MyException.logExceptionMessage(e);
                isconn = false;
                System.out.println("正在尝试重新连接...");
            }
        }
    }
    public static void connect() throws Exception {
        socket = new Socket("127.0.0.1",9999);
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        isconn = true;
        if(isconn){
            new Thread(new ClientListen(socket,ois)).start();
            new Thread(new ClientSend(socket,oos)).start();
            new Thread(new ClientHeart(socket,oos)).start();
        }
    }
    public static void reconnect(){
        while(!isconn) {
            System.out.println("正在尝试重新连接");
            try {
                connect();
                Thread.sleep(3000);
            } catch (Exception e) {
                MyException.logExceptionMessage(e);
            }
        }
    }
}
